//
//  XSFMDBManger.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/11/12.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSFMDBManger.h"
#import <FMDatabase.h>

@interface XSFMDBManger ()

@property(nonatomic,strong)FMDatabase *db;

@end

@implementation XSFMDBManger

+ (instancetype)instance{
    static XSFMDBManger *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [XSFMDBManger new];
        [manager initDataBase];
    });
    return manager;
}

- (void)initDataBase{
    NSString *filePath = [[XSFileManager documentPath] stringByAppendingPathComponent:@"errorLog.sqlite"];
    
    _db = [FMDatabase databaseWithPath:filePath];
    
    [_db open];
    
    NSString *createTableSQL = @"CREATE TABLE 'errorLogTable' ('timestamp' int,'datestr' VARCHAR(255),'log' text)";
    
    BOOL createOK = [_db executeUpdate:createTableSQL];
    if (createOK) {
        NSLog(@"create tb ok");
    }else{
        NSLog(@"create tb faile");
    }
    
    [_db close];
}

- (NSMutableArray *)getAllErrorLogs{
    [_db open];
    NSMutableArray *datarArray = [[NSMutableArray alloc]init];
    FMResultSet *res = [_db executeQuery:@"select * from  errorLogTable"];
    while ([res next]) {
        Model *m = [Model new];
        m.timestamp = [[res stringForColumn:@"timestamp"]integerValue];
        m.datestr = [res stringForColumn:@"datestr"];
        m.log = [res stringForColumn:@"log"];
        
        [datarArray addObject:m];
    }
     
    [_db close];
    
    return datarArray;
}

- (void)deleteAllErrorLogs{
    [_db open];
    [_db executeUpdate:@"delete from errorLogTable"];
    [_db close];
}

- (void)insertErrorLog:(NSString *)errorLogs{
    NSDate *date = [NSDate date];
    NSTimeInterval timestamp = [date timeIntervalSince1970];
    NSDateFormatter *fm = [NSDateFormatter new];
    fm.dateFormat = @"MM-dd HH:mm:ss";
    NSString *datestr = [fm stringFromDate:date];
//    Model *m = [Model new];
//    m.timestamp = timestamp;
//    m.date = datestr;
//    m.log = errorLogs;
    
    [_db open];
 
    BOOL insertOk = [_db executeUpdate:@"insert into errorLogTable(timestamp,datestr,log) values(?,?,?)",@(timestamp),datestr,errorLogs];
    if (insertOk) {
        NSLog(@"insert ok");
    }else{
        NSLog(@"insert fail");
    }
         
    [_db close];
}

@end
